/**
 * Database Cache Search, Set
 * extObj in setting: Api request params
 *
 * @author: Merjiezo
 * @since: 2018-08-14
 * @version 1.3.0
 */
import selectLogic from './selectLogic'
import { throttle } from 'throttle-debounce'
import * as reqArr from './api/filter'

function setReqData(reqData, val, filterArr) {
  let currentVal = val.trim()
  if (currentVal === '') {
    reqData[filterArr[0]] = ''
  } else {
    reqData[filterArr[0]] = currentVal
  }
  reqData.rownum = '10'
}
// [feature request] 效率上优化
export default {
  name: 'remote-codemap-select',

  render(h) {
    let vm = this
    let { componentType } = this
    let on = {
      // tab: vm.handleTabEvt,
    }
    let attrs = {
      disabled: vm.disabled,
      placeholder: vm.placeholder,
      dropWidth: vm.dropWidth
    }
    if (componentType === 'search') {
      attrs['remote-call'] = vm.handleRemoteCallSearch
      attrs['formatter-item-func'] = vm.handleFormatterItemFunc
      on['trigger-item-click'] = this.handleChange
    } else {
      attrs.remote = true
      attrs['remote-call'] = vm.handleRemoteCall
      on['active-change'] = this.handleChange
    }
    return h('ep-' + componentType, {
      ref: 'select',
      staticClass: 'base-select-input',
      attrs,
      on,
      /***
       * 小心升级Vue，如此实现有可能会带来兼容性的问题（Vue Version: 2.5.13）
       * 原因：此代码从vue-loader打包后的代码里抓取，不对应用层开发人员暴露
       */
      model: {
        value: vm.form[vm.name],
        callback: function (t) {
          vm.$set(vm.form, vm.name, t)
        },
        expression: 'form[name]'
      }
    })
  },

  mixins: [selectLogic],

  props: {
    // 扩展请求字段在此
    componentType: {
      type: String,
      default: 'select'
    },
    extData: {
      type: Object,
      default() {
        return {}
      }
    },
    searchKey: {
      type: String,
      default: 'param'
    }
  },

  created() {
    this.apiRequest = throttle(200, (val, callback) => {
      let { filterArr, dbSet } = this.setting
      val = '' + val
      let reqData = {}
      reqData[this.searchKey] = val.trim()
      let queryKey = dbSet.api || ''
      if ('' === queryKey) {
        callback.error('配置失败')
      }
      Object.assign(reqData, this.extData)
      reqArr[queryKey](reqData)
        .then(json => {
          this.setVal(json.data, filterArr, callback)
        })
        .catch(e => {
          callback.error('码表参数获取失败')
        })
    })
  },

  methods: {
    triggerSearch(val) {
      this.$refs.select.setRemoteValue(val || '', true)
    },
    // 为了兼容性
    handleRemoteCall(val, oldVal, callback) {
      this.apiRequest && this.apiRequest(val, callback)
    },
    handleRemoteCallSearch(val, callback) {
      this.apiRequest && this.apiRequest(val, callback)
    },
    handleFormatterItemFunc(item) {
      let { filterArr } = this.setting
      if (filterArr.length > 1) {
        return `${item[filterArr[0]]} [${item[filterArr[1]]}]`
      } else {
        return `${item[filterArr[0]]}`
      }
    },

    getCurrentVal() {
      let currentVal = this.$refs.select.value
      this.triggerSearch(currentVal)
    },

    /***
     * 触发主动赋值
     * 必须要等到数据赋值之后再触发此API，不然会导致不执行的问题
     */
    triggerSet() {
      this.$nextTick(_ => {
        this.$refs.select.setActiveToCurrentVal()
        this.getCurrentVal()
      })
    }
  },

  beforeDestroy() {
    this.apiRequest && (this.apiRequest = null)
  }
}
